/**
 * 封装消息类型
 * 
 */
function chat(data){

  var ct = this;
  this.conn = null;
  this.bosh_server = data.bosh_server;
  this.of_pwd = 'jsepc1!';
  this.domain = data.domain;
  
  this.groupmodel = "dlxxgroupchat";
  this.usercount = data.usercount;
  this.u_nickname = data.u_nickname; //个人昵称
  this.u_imageurl = data.u_imageurl; //个人图片头像
  this.ujid = this.usercount+"@"+this.domain;
  this.chat_contextPath = data.chat_contextPath;
  this.chat_im_images_url = data.chat_im_images_url; //企信文件服务地址
  this.chat_im_download = data.chat_im_download;//企信文件下载地址
  
  this.conn = new  Strophe.Connection(this.bosh_server);
  this.sendpingtimer = 1000*50;
  //消息发送状态  1发送成功，0发送失败 2正在发送 3 无状态
  this.msgSendStatus = {success : "1",fail :"0" ,waitSend:"2" ,nostatus :"3"};
  //消息类型 msgType:0文本,1文件，3图片，4语音、5LBS、6视频 ,7 提示类消息
  this.msgType = {text:"0" , file:"1" ,pic:"3",voice:"4",lbs:5,vedio:"6" ,msg:"7"};
  //会话类型
  this.sessionType = {chat:"0" , groupchat:"1",chatE:"chat" , groupE:"groupchat"};//单聊0群聊1
  //是否有新消息
  this.isread={news:"1",nomsg:"0"};//1有新消息,0没有新消息
  //是否发送或是接收消息
  this.incom = {receve:"0" , send:"1"} ;      //0 接收，1 发送
  this.sessionObjectParam = {
		  content:"", // 消息内容 如果3，1则是{ext:扩展名,orgName:原文件名,fileid:文件id,fileName:上传后的文件名}
		  from :ct.usercount,  // 本人帐号
		  to:"" , // 对方 聊天人账号 //发送消息，对方to id是空的,接收消息to是有的
		  roomid:"",//群id 
		  incom:"" , //0 接收，1 发送
		  isread:"" , //是否有消息1有新消息，0没有新消息
		  sendtime :"", //会话，聊天时间
		  sessionType:"" , //会话类型，值对应[ this.sessionType] 0 用户 ,1 群   
		  sendStatus :"", //发送状态 值对应[this.msgSendStatus]1发送成功， 0发送失败 2正在发送 3无状态
		  msgType:"", //消息类型,值对应[this.msgType ]  msgType:0文本,1文件，3图片，4语音、5LBS、6视频
		  userImage:"",//用户头像
		  msgId:"1" //消息id,默认1 后台生成
			  
  };
  
  /**消息记录*/
  this.chatMsgObject = {
		  msgid:"消息id",
		  incom:"",  //0 接收，1 发送
		  uname:"", //用户帐号
		  userImage:"", //用户头像 
		  sendStatus:"", //发送状态 ,只有发送方有 值对应[this.msgSendStatus]
		  msgType:"",    //消息类型,值对应[this.msgType ] 0文本,1文件，3图片
		  content:"",    //如果等0则消息内容，如果3，1则是{ext:扩展名,orgName:原文件名,fileid:文件id,fileName:上传后的文件名}
		  sendtime:"",   //会话，聊天时间
		  sesUserInfo:{name:"用户真实姓名",imageurl:"图片地址"},
		  sesFromUserInfo:{name:"用户真实姓名",imageurl:"图片地址"},
  		  sesGroupInfo:{name:"用户真实姓名",imageurl:"图片地址"} //群信息
  };
  
  /**
   * 文件对象
   * {ext:扩展名,orgName:原文件名,fileid:文件id,fileName:上传后的文件名}
   */
  this.fileDataObject = {
		  ext:"扩展名",
		  orgName:"原文件名",
		  fileid:"文件id",
		  fileName:"上传后的文件名"
		};

  
  //登录连接
  this.onConnect = function(){
	  ct.conn.connect(ct.ujid,ct.of_pwd,  function(status){
		  if (status == Strophe.Status.CONNECTING) {
			  	ct.log('正在连接...');
		        console.log('Strophe is connecting.');
		    } else if (status == Strophe.Status.CONNFAIL) {
		    	//ct.log('Strophe failed to connect.');
		    	ct.log('连接断开  <span onclick=chatObject.onConnect(); style=cursor:pointer; >点击重连</span>');
		    } else if (status == Strophe.Status.DISCONNECTING) {
		    	ct.log('正在连接...');
		    } else if (status == Strophe.Status.DISCONNECTED) {
		    	//ct.log('Strophe is disconnected.');
		    	ct.log('连接断开 <span onclick=chatObject.onConnect(); style=cursor:pointer; >点击重连</span>');
				//$('#connect').get(0).value = 'connect';
		    } else if (status == Strophe.Status.CONNECTED) {
				ct.log('连接成功！');
				$.cookie('jid', ct.conn.jid);
				$.cookie('sid', ct.conn.sid);
				$.cookie('rid', ct.conn.rid);
				
				var handler = function(){
		        	ct.prototy.send_ping(ct.domain);
		        };
				var timerPing = setInterval( handler , 5000); //50秒发一次ping包 ct.sendpingtimer
				
				ct.prototy.addListen();
				//发送我上线
				ct.conn.send($pres().tree());
		    }
	  });
	  
	  
  };
  
  
  //日志输出
  this.log=function(msg){
	  //$("#log").append("<p>"+msg+"</p>");
	  $('#log').html(msg);
	//$('#log').append('<div></div>').append(document.createTextNode(msg));
  };
 
  /**
   * 消息反序列
   * @param data data数据
   * @type 发送类型
   */
  this.msg_parseText = function (data ,type){
	  if(type==this.msgType.text){
		return data;
	  }else{
		  return "{\"content\":"+data+"}";
	  }
  };
  
  this.prototy = {
		    deleteHandler:function(){
	  		ct.conn.deleteHandler(this.onMessage);
	  		ct.conn.deleteHandler(this.handle_pong);
	  		ct.conn.deleteHandler(this.pkidMessage);
	  		ct.conn.deleteHandler(this.prececeOnOfLine);
  		 },
	     //begin
  		addListen:function(){
  			//add onMessage消息监听
			ct.conn.addHandler(this.onMessage, null, 'message', null, null,  null);
			ct.conn.addHandler(this.handle_pong, null, 'iq', null,  'ping1'); 
			ct.conn.addHandler(this.pkidMessage, null, 'iq', null,  null,null); 
			ct.conn.addHandler(this.prececeOnOfLine, null, 'presence', null,  null,null); 
  		 },
  		 //监听在线状态
  		prececeOnOfLine:function(pre){
  			 var from = pre.getAttribute('from');
  			 var elems_msg_online = msg.getAttribute('type');
  			 if(elems_msg_online!=null && elems_msg_online=="unavailable"){
  				 //离线，通过from更新通讯录列表
  				 
  			 }else{
  				 //在线
  			 }
  		},
  		handle_pong: function(iq) {
  			// alert("cc111");
  			// alert(Strophe.getText(iq));
  		    //ct.log(Strophe.serialize(iq)+"");
  		    return true;
  		},
  		 //发送ping包
  		send_ping:function(to){
  			 var ping = $iq({to: to, type: "get", id: "ping1"}).c("ping", {xmlns: "urn:xmpp:ping"});
  			 ct.conn.sendIQ(ping);
  		 },
		//消息监听
  		onMessage:function(msg){
  			try{ 
		  			var to = msg.getAttribute('to');
		  		    var from = msg.getAttribute('from');
		  		    var type = msg.getAttribute('type'); //消处类型 //chat/grouupchat
		  		    var msgid = msg.getAttribute('id'); //消息id
		  		    var msgType = msg.getAttribute('msgType'); //消息类型
		  		    
		  		    var elems_msg_thread = msg.getElementsByTagName('thread');//消息规则定义/chat/groupchat/....
		  		    var elems_msg_event = msg.getElementsByTagName('event');//提醒订阅类消息
		  		    var body_elems = msg.getElementsByTagName('body');
		  		  if (type == "chat" && body_elems.length > 0 && elems_msg_thread.length > 0 ) {
			  	    	//body格式
			  	    	var body = body_elems[0];//<body><![CDATA[{age:'http://www.aa',sex:'男',name:'邵年文'}]]></body>
			  	    	var bodycontent = Strophe.getText(body);
			  	    	var encode_elements = msg.getElementsByTagName('encode');//是否base64加密
			  	    	if(encode_elements.length>0 && Strophe.getText(encode_elements[0])=="0"){
			  	    		bodycontent= utf8to16(base64decode(bodycontent))  ;
			  	    	}
			  	    	var sendtime = "";
			  	    	var sendTime_elements = msg.getElementsByTagName('immessagetime');//发送时间
			  	    	if(sendTime_elements.length>0 ){
			  	    		sendtime= Strophe.getText( sendTime_elements[0]) ;
			  	    		sendtime = sendtime.substring(0, sendtime.length-3);
			  	    	}
			  	        var contentJson = bodycontent.replace("<![CDATA[","");
			  	        contentJson = contentJson.replace("]]>","");
			  	        
			  	        if(Strophe.getText(elems_msg_thread[0])==ct.sessionType.chatE){
			  	        	//处理单聊
			  	        	ct.prototy.processMsg(msgType,sendtime,contentJson,"", from ,msgid, ct.sessionType.chat );
			  	           
			  	        }else if(Strophe.getText(elems_msg_thread[0])==ct.sessionType.groupE){
			  	        	var roomid_elements = msg.getElementsByTagName('roomid');  //群id
				  	      	var roomid = "";
				  	      	if(roomid_elements.length>0){
				  	      		roomid = Strophe.getText(roomid_elements[0]);
				  	      	}
				  	      	//处理群聊
				  	      ct.prototy.processMsg(msgType,sendtime,contentJson, roomid,from ,msgid, ct.sessionType.groupchat );
			  	        }
		  	       }
		  		  //订阅类
		  		  if(type == "chat" &&  elems_msg_thread.length > 0 && elems_msg_event.length > 0){
		  			  var threadText = Strophe.getText(elems_msg_thread[0]);
		  			  var eventText = Strophe.getText(elems_msg_event[0]);
		  			  //订阅类消息先发回执
		  			 ct.prototy.sendIQRepy(msgid);
		  			  if(threadText=="afriend"){
		  				  var subfrom = Strophe.getText(msg.getElementsByTagName('subfrom')[0]);
		  				  var subto = Strophe.getText(msg.getElementsByTagName('subto')[0]);
		  				  
		  				var msgid_value = $.cookie(msgid);
		  				if(msgid_value==undefined){
		  					var cookietime = new Date(); 
		  					cookietime.setTime(cookietime.getTime() + (1000*60));//coockie保存一分钟
		  					
		  					 $.cookie(msgid,msgid,{expires:cookietime});
		  					 ct.prototy.processSubAfriend(eventText,subfrom , subto,msgid);
		  				}
		  			  }
		  			 if(threadText=="groupchat"){//群
		  				var msgid_value = $.cookie(msgid);
		  				if(msgid_value==undefined){
		  					var cookietime = new Date(); 
		  					cookietime.setTime(cookietime.getTime() + (1000*60));//coockie保存一分钟
		  					
		  					 $.cookie(msgid,msgid,{expires:cookietime});
		  					 ct.prototy.processSubGroup(eventText,from , to,msg);
		  				}
		  			  }
		  		  }
		  		  
		  		  //消息发送异常或服务器拒绝发送，如群，群被踢除
		  		  if(type=="error"){
		  			 ct.prototy.processErrorMsg(msgid);
		  		  }
  			}catch(e){
  				//alert(e);
  				//出现异常 
  				console.log('异常 onmsg listen.');
  				ct.prototy.sendIQRepy(msgid); //发送错误消息回执 重新修复监听
  				ct.prototy.deleteHandler();
  	  		    ct.prototy.addListen(); 
  			}
  		  return true;
  		 },
  		 /**
  		  * 处理好友订阅消息
  		  */
  		 processSubAfriend:function(eventText,subfrom , subto,msgId){
  			if(eventText=="subscribe"){
  				messageDialogChatBox.BuddyAuthentication(eventText,subfrom , subto);
  			}else if(eventText=="subrejection"){
  				//alert(msgId);
  				messageDialogChatBox.SubrejectionAuthentication(eventText,subfrom , subto);
  			}else if(eventText=="subaccp"){
  				//alert(msgId);
  				messageDialogChatBox.SubaccpAuthentication(eventText,subfrom , subto);
  			}else if(eventText=="subdel"){
  				//TODO 需要重新load通讯录
  				ct.prototy.getuserSession();
  				sidebar_User.loadUsers();//hzong 增加刷新好友列表
  			}
  			
  		 },
  		/**
  		  * 处理群订阅消息
  		  */
  		 processSubGroup:function(eventText,subfrom , subto,msg){
//  			if(eventText=="subscript"){//群提示-接收 【创建群邀请成员】-【邀请群成员】
//  				var groupName =msg.getElementsByTagName('groupName')[0];//群名称
//  				var groupId =msg.getElementsByTagName('roomid')[0];//群id
//  				var members =msg.getElementsByTagName('body')[0];//群成员
//  				alert(groupName+"-"+groupId+"-"+members);
//  			}else if(eventText=="exgroup"){//群提示-【退出群】-接收
//  				
//  				//alert(msgId);
////  				messageDialogChatBox.SubrejectionAuthentication(eventText,subfrom , subto);
//  			}else if(eventText=="kickmem"){
//  				//alert(msgId);
////  				messageDialogChatBox.SubaccpAuthentication(eventText,subfrom , subto);
//  			}else if(eventText=="upgroup"){
////  				//TODO 需要重新load通讯录
////  				sidebar_User.loadUsers();//hzong 增加刷新好友列表
//  			}
  		 },
  		 /**
  		  * 处理群聊
  		  * @param msgType消息类型
  		  * @param sendtime 发送时间服务器为主
  		  * @param contentJson 消息串json string {sendtime:'',msgType:'',content:object}
  		  * @param to_roomid 群id 
  		  * @param to tojid 谁发来的消息id 不能为空
  		  * @param msgid 消息id
  		  * 
  		  * msgtype 消息类型  ct.sessionType.groupchat/ct.sessionType.chat
  		  */
  		 processMsg:function(msgType,sendtime,contentJson,to_roomid,tojid ,msgid,msgtype){
  			 //hzong 预防
  			var msgid_value = $.cookie(msgid);
			if(msgid_value !=undefined){
				return;
			}else{
				var cookietime = new Date(); 
				cookietime.setTime(cookietime.getTime() + (1000*60));//coockie保存一分钟
				$.cookie(msgid,msgid,{expires:cookietime});
			}
  			 
  			//判断当前窗口是否为当前会话窗口,如果是追加一条，否则创建一条新会话 表示有新消息汽泡 groupchat_roomid
  			var fromJid =  $(".content_nav").attr("tojid"); 
  			var to_fromJid = "";
  			var sessionType = ct.sessionType.groupchat;
			if(msgtype ==  ct.sessionType.groupchat ){
				to_fromJid = "groupchat_"+to_roomid;
				tojid = tojid.substring(0,tojid.indexOf("@"));
				sessionType = ct.sessionType.groupchat;
			}else if(msgtype ==   ct.sessionType.chat){
				sessionType = ct.sessionType.chat;
				tojid = tojid.substring(0,tojid.indexOf("@"));
				to_fromJid = "chat_"+tojid;
			}
  			 
  			//是否新消息标记 ,如果聊天窗口正与当前人聊天,则消息不为新消息
  			var newMsg = ct.isread.news ;
  			if(fromJid!=undefined && to_fromJid==fromJid){
  				newMsg = ct.isread.nomsg;
  			}
  			// to:"" , // 对方 聊天人账号 //发送消息，对方to id是空的,接收消息to是有的
  			//  roomid:"",//群id 
  			//设置参数
	     	 ct.sessionObjectParam.incom=ct.incom.receve;
	     	 ct.sessionObjectParam.isread=newMsg;
	     	 ct.sessionObjectParam.sessionType=sessionType;
	     	 ct.sessionObjectParam.to = tojid;
	     	 ct.sessionObjectParam.roomid = to_roomid;
	     	 ct.sessionObjectParam.sendStatus=ct.msgSendStatus.nostatus;
	     	 ct.sessionObjectParam.content= contentJson;
	     	 ct.sessionObjectParam.msgId= msgid;
	     	 ct.sessionObjectParam.msgType = msgType; //设置消息类型
	     	 ct.sessionObjectParam.sendtime = sendtime;
	     	ct.sessionObjectParam.userImage = ct.u_imageurl;
  			//设置会话已读 obj = chatMsgObject
	     	ct.prototy.sendIQRepy(msgid);
	     	ct.prototy.setchatlogReObjListen(ct.sessionObjectParam,function(flg,obj){
	     		 	if(flg=="1"){
  					//设置聊天记录成功,发送回执
  					//如果是新消息追加一条，否则刷新会话
  					if(newMsg ==ct.isread.news){
  						ct.prototy.getuserSession();
  					}else{
  						
  						var str = ct.prototy.lmORrm( obj);
  						 $(".main_nav_tell").append( str);
  						$('.fancybox').fancybox();
  						//始终保最滚动条最后一条显示
  						ct.prototy.divScoroll();
  					}
  				}else{
  					//如果出现异常 ，消息监听则会失效，重新添加监听，将错误消息发送回执
  					ct.prototy.deleteHandler();
  					ct.prototy.addListen();
  					ct.prototy.sendIQRepy(msgid);
  				}
  			});
	     	return;
  		 },
  		 /**
  		  * 发消息
  		  */
  		 sendMsg : function(msgtype,text,to){
  			 if(text=="")
  				 return;
  			 var msgid = to+"_"+this.getTimeRndString();
  			 var sendtime = new Date().pattern("yyyy-MM-dd HH:mm:ss");
  			 var content = ct.msg_parseText(text , msgtype);
  		     var reply = $msg({to:to+"@"+ct.domain , from: ct.ujid, type: 'chat' ,id:msgid,msgType:msgtype})
		     .c('encode',"0").up()
		     .c('thread',"chat").up() 
		     .c("body").cht(content);
  		    
  	  	    //文本追加内容
 	  	    this.appendSendContent(msgtype,msgid,content,sendtime);
 	  		//清空内容
		    $("#editArea").val("");
		    
 		     //发送
  		     this.send(reply);
  		     this.testingSendStatus(msgid);
  		     
  		     //创建会话
  		     ct.sessionObjectParam.content = content;
  		     ct.sessionObjectParam.to = to;
  		     ct.sessionObjectParam.roomid="";
  		     ct.sessionObjectParam.incom=ct.incom.send;
  		     ct.sessionObjectParam.isread =ct.isread.nomsg; 
  		     ct.sessionObjectParam.sendtime = sendtime;
  		     ct.sessionObjectParam.sessionType = ct.sessionType.chat; // ct.sessionType.chat groupchat
  		     ct.sessionObjectParam.sendStatus =  ct.msgSendStatus.waitSend; 
  		     ct.sessionObjectParam.msgType = msgtype;
  		     ct.sessionObjectParam.msgId = msgid;
  		     ct.sessionObjectParam.userImage =  ct.u_imageurl;
  		     
  		     
		     this.setchatlogReObjListen(ct.sessionObjectParam ,function(flg){});
  		 },
  		 /**
  		  * 发送群消息
  		  * @msgtype 消息类型
  		  * @text 文本 {\"msgType\":\"0\",\"content\":\""+msg+"\",\"sendtime\":\""+sendtime+"\"}
  		  * @param roomid房间id
  		  */
  		 sendGroupMsg:function(msgtype,text,roomid){
  			if(text=="")
  				 return;
  			var to_group = roomid+"@"+ct.groupmodel+"." + domain;
  			var msgid = roomid+"_"+this.getTimeRndString();
  			 var sendtime = new Date().pattern("yyyy-MM-dd HH:mm:ss");
  			 var content = ct.msg_parseText(text , msgtype);
	  	    var reply = $msg({to: to_group, from: ct.ujid, type: 'groupchat' ,id:msgid ,msgType:msgtype})
	  	    .c('thread','groupchat').up()
	  	    .c('event','chat').up()
	  	    .c('roomid',roomid).up()
	  	    .c('from', ct.usercount).up()
	  	    .c('encode',"0").up()
	  	    .c('body').cht(content);
	  	     
	  	    
	  	    //文本追加内容
	  	    this.appendSendContent(msgtype,msgid,content,sendtime);
	  	    
	  	    //清空文本内容
	  	    $("#editArea").val("");
		    
	  	    //创建会话
 		     ct.sessionObjectParam.content = content;
 		     ct.sessionObjectParam.to = "";
 		     ct.sessionObjectParam.roomid=roomid;
 		     ct.sessionObjectParam.incom=ct.incom.send;
 		     ct.sessionObjectParam.isread =ct.isread.nomsg; 
 		     ct.sessionObjectParam.sendtime = sendtime;
 		     ct.sessionObjectParam.sessionType = ct.sessionType.groupchat; // ct.sessionType.chat groupchat
 		     ct.sessionObjectParam.sendStatus =  ct.msgSendStatus.waitSend; 
 		     ct.sessionObjectParam.msgType = msgtype;
 		     ct.sessionObjectParam.msgId = msgid;
 		     ct.sessionObjectParam.userImage =  ct.u_imageurl;
		     this.setchatlogReObjListen(ct.sessionObjectParam ,function(flg){});
		    //发送
		    this.send(reply);
		    this.testingSendStatus(msgid);
  		 },
  		 /**
  		  * @param xml报文
  		  */
  		 send:function(xml){
  			ct.conn.send(xml.tree());
  		 },
  		 /**
  		  * 发送加好友邀请
  		  * @param to 邀请谁
  		  */
  		 sendInvite:function(to){
  			var msgid = to+"_"+this.getTimeRndString();
  			var reply = $msg({to: to, from: ct.ujid, type: 'chat' ,id:msgid ,msgType:ct.msgType.msg})
	  	    .c('thread','afriend').up()
	  	    .c('event','subscribe').up()
	  	    .c('subfrom',ct.ujid).up()
	  	    .c('subto',to).up();
	  	    this.send(reply);
  		 },
  		 /**
  		  * 发送拒绝订阅
  		  */
  		 sendSubReg:function(subfrom){
  			var msgid = subfrom+"_"+this.getTimeRndString();
  			var reply = $msg({to: subfrom, from: ct.ujid, type: 'chat' ,id:msgid ,msgType:ct.msgType.msg})
	  	    .c('thread','afriend').up()
	  	    .c('event','subrejection').up()
	  	    .c('subfrom',subfrom).up()
	  	    .c('subto',ct.ujid).up();
	  	    this.send(reply);
  		 },
  		 /**
  		  * 接受订阅
  		  */
  		 sendAccp:function(subfrom){
  			var msgid = subfrom+"_"+this.getTimeRndString();
  			var reply = $msg({to: subfrom, from: ct.ujid, type: 'chat' ,id:msgid,msgType:ct.msgType.msg })
	  	    .c('thread','afriend').up()
	  	    .c('event','subaccp').up()
	  	    .c('subfrom',subfrom).up()
	  	    .c('subto',ct.ujid).up();
	  	    this.send(reply);
  		 },
  		 /**
  		  * 发送订阅删除
  		  */
  		 sendSubDel:function(to){
  			var msgid = to+"_"+this.getTimeRndString();
  			var reply = $msg({to: to, from: ct.ujid, type: 'chat' ,id:msgid ,msgType:ct.msgType.msg})
	  	    .c('thread','afriend').up()
	  	    .c('event','subdel').up()
	  	    .c('subfrom', ct.ujid).up()
	  	    .c('subto',to).up();
	  	    this.send(reply);
  		 },
  		 /**
  		  * 邀请入群
  		  * @param member 邀请成员帐号,多个,号隔开
  		  * @param roomid 群id
  		  */
  		 sendInviteGroup:function(roomid,member){
  			var to_group = roomid+"@"+ct.groupmodel+"." + domain;
  			var msgid = roomid+"_"+this.getTimeRndString();
  			var reply = $msg({to: to_group, from: ct.ujid, type: 'groupchat' ,id:msgid ,msgType:ct.msgType.msg  })
	  	    .c('thread','groupchat').up()
	  	    .c('event','subscript').up()
	  	    .c('roomid',roomid).up()
	  	    .c('body',member).up();
	  	     this.send(reply);
  		 },
  		 /**
  		  * 接收回执
  		  */
  		pkidMessage:function(iq){
  			var pkid_elems = iq.getElementsByTagName('pkid');
  			 if(pkid_elems.length > 0 ){
  				 var pkidRepy = Strophe.getText(pkid_elems[0]);
  				 //将消息发送成功状态保存至cookie 50秒检测
  				 //$.cookie(pkidRepy , ct.msgSendStatus.success); 
  				 //消息发送成功回执
  				
  				 //1发送成功，0发送失败  2正在发送 3 无状态
  				 var objects =  $(".main_nav_tell").find(".main_nav_tell_left[attmsgid='"+pkidRepy+"']");
  				 var t = $(objects).find(".news_nav").find('.con_ico');
  				 $(t).attr("status" , ct.msgSendStatus.success);
  				 $(t).find("img").attr("src",ct.chat_contextPath+"images/success.png");
  				 /**
  				  * ajax更新消息状态发送成功
  				  */
  				 
  				 $.post(ct.chat_contextPath+"chatCacheController/setmsgstatus.html",{status:ct.msgSendStatus.success,msid:pkidRepy},function(obj){
  					//obj==000 成功
  				 });
  			 }
  			return true;
  		 }, 
  		 
  		 processErrorMsg:function(msgid){
				 //将消息发送成功状态保存至cookie 50秒检测
				 //$.cookie(pkidRepy , ct.msgSendStatus.success); 
				 //消息发送成功回执
				
				 //1发送成功，0发送失败  2正在发送 3 无状态
				 var objects =  $(".main_nav_tell").find(".main_nav_tell_left[attmsgid='"+msgid+"']");
				 var t = $(objects).find(".news_nav").find('.con_ico');
				 $(t).attr("status" , ct.msgSendStatus.fail);
				 $(t).find("img").attr("src",ct.chat_contextPath+"images/failure.png");
				 /**
				  * ajax更新消息状态发送成功
				  */
				 
				 $.post(ct.chat_contextPath+"chatCacheController/setmsgstatus.html",{status:ct.msgSendStatus.fail,msid:msgid},function(obj){
					//obj==000 成功
				 });
  		 },
  		 /**
  		  * 50秒检测是否发送成功,否则更新失败
  		  * @param pkidRepy 消息id
  		  */
  		 testingSendStatus:function(pkidRepy){
  			 setTimeout(function(){
  				 var objects =  $(".main_nav_tell").find(".main_nav_tell_left[attmsgid='"+pkidRepy+"']");
  				 var t = $(objects).find(".news_nav").find('.con_ico');
  				 if($(t).attr("status")!=ct.msgSendStatus.success){
  					 $(t).attr("status" , "0");
  					 $(t).find("img").attr("src",ct.chat_contextPath+"images/failure.png");
  					 /**
  					  * 成功状态由回执包发送
  					  */
  					 $.post(ct.chat_contextPath+"chatCacheController/setmsgstatus.html",{status:ct.msgSendStatus.fail,msid:pkidRepy},function(obj){
  						//obj==000 成功
  					 });
  				  } 
  			 },70000*10); //70秒检测是否发送成功,否则更新失败
  			 return;
  		 },
		/**
		 * 消息发送回执
		 * @return
		 */
		sendIQRepy:function(msgid){
			//设置有新消息会话
			var iq = $iq({type: 'set'}).c('pkid',msgid);
			 ct.conn.sendIQ(iq);
			 return;
		},
		/**
		 * 追加发送内容
		 * @param msgtype 消息类型 
		 * @param msgid 消息id
		 * @param jsonObject json对象
		 * @param sendtime 发送时间
		 * @param object chatMsgObject
		 */
		 appendSendContent:function(msgtype,msgid,jsonObject,sendtime){
			 ct.chatMsgObject.incom = ct.incom.send;
		  	 ct.chatMsgObject.msgid = msgid;
		  	 var sesUserData = {};
			 sesUserData.name = ct.u_nickname;
			 sesUserData.imageurl  = ct.u_imageurl;
			 ct.chatMsgObject.uname=sesUserData.name;
			 ct.chatMsgObject.userImage=sesUserData.imageurl; 
			 ct.chatMsgObject.sendStatus=ct.msgSendStatus.waitSend;
			 ct.chatMsgObject.msgType= msgtype;
			 
			 
			  var s = jsonObject;
			
			 if(msgtype==ct.msgType.text){
				  ct.chatMsgObject.content=s;
			  }else if(msgtype==ct.msgType.file || ct.msgType.pic){
				  if(typeof(s)=='string'){
					  	s = eval("("+jsonObject+")");
				   }
				  var fileobj = s.content;
				  if(typeof(s.content)=='string'){ 
				    fileobj = eval("("+s.content+")");
				  }
				 ct.fileDataObject.ext = fileobj.ext;
				 ct.fileDataObject.orgName = fileobj.orgName;
			     ct.fileDataObject.fileid = fileobj.fileid;
			     ct.fileDataObject.fileName = fileobj.fileName;
			     ct.chatMsgObject.content = ct.fileDataObject;
			  }
			  ct.chatMsgObject.sendtime=sendtime; //会话，聊天时间
			  ct.chatMsgObject.sesUserInfo=sesUserData;
			  var str = this.lmORrm( ct.chatMsgObject);
			  $(".main_nav_tell").append(str);
			  $('.fancybox').fancybox();
			  this.divScoroll();
		 },
		//表情替换
		replace_em:function (str){
			if(str==""){
				return "";
			}else{
				str = str.replace(/\</g,'&lt;');
				str = str.replace(/\>/g,'&gt;');
				str = str.replace(/\n/g,'<br/>');
				str = str.replace(/\[em_([0-9]*)\]/g,'<img src="'+ct.chat_contextPath+'images/arclist/$1.gif" border="0" />');
				return str;
			}
		},
		getTimeRndString:function () {
			   var tm=new Date();
			   var str=tm.getMilliseconds()+tm.getSeconds()*60+tm.getMinutes()*3600+tm.getHours()*60*3600+tm.getDay()*3600*24+tm.getMonth()*3600*24*31+tm.getYear()*3600*24*31*12;
			   return "webim"+str;
		},
		/**
		 * 加载错误图片
		 * @param o 图片对象
		 * @param stype 会话类型
		 */
		loaderr_img:function(o,stype){
			if(stype==ct.sessionType.chat){
				//单头像
				$(o).attr("src",ct.chat_contextPath+"images/tou.png");
			}else{
				$(o).attr("src",ct.chat_contextPath+"images/more_pp.png");
			}
		},
		/**
		 * 此方法专为聊天服务图片传输类
		 */
		loaderr_fileImg:function(o){
			$(o).attr("src",ct.chat_contextPath+"images/errorfile.png");
		},
		/**
		 * 显示聊天窗口层
		 */
		dis_chat_win:function(){
			$('#tab_nav').find('.main_right').find('.content_nav').show();
		},
		/**
		 * 消息永远保持最后一条显示
		 */
		divScoroll:function(){
			 var div = $('.main_right_nav');
			 div.scrollTop(div[0].scrollHeight);
		},
		/**
		 * @ext 文件扩展名
		 */
		dis_upfile_type_img:function(ext){
		  	var imageattr = ct.chat_contextPath+"/images/doc/ico_xx.png";
			if(ext=='txt'){
				imageattr=ct.chat_contextPath+"/images/doc/ico_t.png";
			}else if(ext=='doc' || ext=='docx'){
				imageattr=ct.chat_contextPath+"/images/doc/ico_w.png";
			}else if(ext=='ls' || ext=='xlsx'){
				imageattr=ct.chat_contextPath+"/images/doc/ico_x.png";
			}else if(ext=='ppt' || ext=='pptx'){
				imageattr=ct.chat_contextPath+"/images/doc/ico-p.png";
			}else if(ext=='zip' || ext=='rar'){
				imageattr=ct.chat_contextPath+"/images/doc/ico_zip.png";
			}else if(ext=='pdf'){
				imageattr=ct.chat_contextPath+"/images/doc/ico_pdf.png";
			}
			return imageattr;
		},
		/**
		 * 发送状态
		 * @incom receve:"0" , send:1
		 * @status 状态;  ct.msgSendStatus = {success : "1",fail :"0" ,waitSend:"2" ,nostatus :"3"};
		 */
		issendMsgStr_status:function(incom,status){
			var str = "";
			if(incom == ct.incom.send){
				//0/1 1发送成功，0发送失败 2正在发送 3 无状态
				if(status== ct.msgSendStatus.success){
					str ="<div class=\"con_ico\" status='"+status+"'><img src=\""+ct.chat_contextPath+"images/success.png\"></div>";
				}else if(status==ct.msgSendStatus.waitSend){
					str ="<div class=\"con_ico\" status='"+status+"'><img src=\""+ct.chat_contextPath+"images/wait.gif\"></div>";
				}else if(status==ct.msgSendStatus.nostatus){
					str ="<div class=\"con_ico\" status='"+status+"'><img src=\""+ct.chat_contextPath+"images/weizhi.png\"></div>";
				}else if(status==ct.msgSendStatus.fail){
					str ="<div class=\"con_ico\" status='"+status+"'><img src=\""+ct.chat_contextPath+"images/failure.png\"></div>";
				}
			} 
			return str;
		},
		/**
		 *   内容对象
		 * 	 this.chatMsgObject = {
		 *	 incom:"",  //0 接收，1 发送
		 *	 uname:"", //用户帐号
		 *	 userImage:"", //用户头像 
		 *	 sendStatus:"", //发送状态 ,只有发送方有 值对应[this.msgSendStatus]
		 *	 msgType:"",    //消息类型,值对应[this.msgType ] 0文本,1文件，3图片
		 *	 content:"",    //如果等0则消息内容，如果3，1则是{ext:扩展名,orgName:原文件名,fileid:文件id,fileName:上传后的文件名}
		 *	 sendtime:"",   //会话，聊天时间
		 *	 sesUserInfo:{name:"用户真实姓名",imageurl:"图片地址"}
		 */
		dis_content_byType:function(object){
			if(object.msgType==ct.msgType.text){
				return "<div class=\"t_nav\">"+this.replace_em(object.content)+"</div>";
			}else if(object.msgType==ct.msgType.pic){
				var obfile = object.content;
				if(typeof(object.content)=='string'){
					obfile = eval("("+object.content+")");
				}
				var image_path = ct.chat_im_images_url+obfile.fileName;
				var st = "<div class=\"t_nav\" ><a  class=\"fancybox\"  href=\""+image_path+"\"  data-fancybox-group=\"gallery\" title=\"\" ><img width=\"100px\" height=\"75px\"   src=\""+image_path+"\" /></a></div>";
				return st;
			}else if(object.msgType==ct.msgType.file){
				var obfile = object.content;
				if(typeof(object.content)=='string'){
					obfile = eval("("+object.content+")");
				}
				var image_path = chat_im_images_url+obfile.fileName;
				var st = "<div class=\"t_nav\" >" +
							"<div class=\"t_nav_left\"><img src=\""+this.dis_upfile_type_img(obfile.ext)+"\"></div>" +
								"<div class=\"t_nav_right\">" +
									"<p>"+obfile.orgName.substring(0,obfile.orgName.lastIndexOf("."))+"</p>"+
									"<div class=\"xiazai\"><a href=\""+ct.chat_im_download.replace("id",obfile.fileid)+"\">下载</a></div>"+
								"</div>" +
						"</div>";
				return st;
			}
		},
		/**
		 * 拼装聊天信息数据
		 * @param object
		 */
		lmORrm:function(object){
			 
			//incom 0 接收，1 发送
			var right_left = object.incom == ct.incom.receve ? "main_nav_tell_right" : "main_nav_tell_left";
			var uname = object.sesUserInfo.name;
			var userImage = object.sesUserInfo.imageurl;
			var str = "<div class='"+right_left+"' attmsgid='"+object.msgid+"' >";
						str+="<div class=\"news_tile\">"+object.sendtime+"</div>";
						str+="<div class=\"news_nav\">";
								str+="<div class=\"tt_pic\"><img alt='"+uname+"'   src=\""+userImage+"\" ></div>";
								str+="<div class=\"tt_left\">";
											//此处动态,图片\文字\文档、lbs、语音等
											str+=this.dis_content_byType(object);
								str+="</div>";
										//发送消息 发送状态 
										str+=this.issendMsgStr_status(object.incom,object.sendStatus);
						str+="</div>";
				str+="</div>";
			return str;
		},
		/**
		 * 获取用户聊天会话
		 */
		getuserSession : function() {
			var data = {username:ct.usercount};
			$.post(ct.chat_contextPath+ "chatCacheController/getsession.html",data,function(obj) {
				try {
					var html = "";
					$.each(obj,function(i, u) {

						var tojid = u.sessionType == ct.sessionType.chat ? "chat_"	+ u.to: "groupchat_"+ u.roomid;
						var uname = "未知";
						var userImage = "";
						if (u.sesUserInfo != undefined) {
							uname = u.sesUserInfo.name;
							userImage = u.sesUserInfo.imageurl;
						}
						html += '<li class="link_nav"><span><img style="width:40px;height:40px;" src="'+ userImage+ '"/>'+ (u.isread == ct.isread.news ? '<i></i>': '')
						+ '</span><p tojid="'	+ tojid	+ '">'	+ uname+ '</p></li>';
					});
				$(".main_left_list ul").eq(0).html(html).find(".link_nav").click(function(){
					ct.prototy.fillBasicInfo(this);
					});
			} catch (e) {
				alert('获取会话异常....chat.js >> getuserSession >> '+ e);
			}
			}, "json");
			return;
					
		},
		fillBasicInfo:function (dom){
		    var name = $(dom).find('p').text();
		    var img = $(dom).find('img')[0].src;
		    var tojid = $(dom).find('p').attr("tojid");
		    msgBox.chat(tojid,name,img);
		},
		/**
		 * 创建聊天会话保存redis 服务中
		 */
		createSessionObject:function(data){
			$.post(ct.chat_contextPath+"chatCacheController/setSession.html",data,function(object){
				if(!object.result){
					alert('设置会话服务器异常+session');
				}
			},"json");
			return;
		},
		/**
		 * 聊天会话对象 ,争对聊天 接收消息
		 * @data 参数 sessionObjectParam
		 * @fun回调
		 */
		setchatlogReObjListen:function(data,fun){
			$.post(ct.chat_contextPath+"chatCacheController/setchatlogReObjListen.html",data,function(json){
				if(!json.result){
					//alert('设置会话服务器异常+lis');
					console.log('设置会话服务器异常 listen.');
					fun('0',"o");
				}else{
					fun('1',json.object);
				}
			},"json");
			return;
		},
		/**
		 * 加载聊天记录
		 * @param to 和谁的聊天
		 */
		loadChatLog:function(to){
			//重置分页
			$("#pageChat").val(0);
			$(".main_nav_tell").html("");
			var data = {from:ct.usercount,to:to};
			$.post(ct.chat_contextPath+"chatCacheController/loadChatLog.html",data,function(object){
				$(".main_nav_tell").html(""); //清空原记录
				$.each(object,function(i,u){
					//u = chatMsgObject
					var str = ct.prototy.lmORrm(u);
					$(".main_nav_tell").append(str);
					
				});
				$('.fancybox').fancybox();
				//加载记录后,消息滚动在最后 一条
				ct.prototy.divScoroll();
			},"json");
			return;
		},
		
		/**
		 * 分页
		 * @param 和谁的聊天记录
		 */
		loadChatLogPage:function(to){
			// 获取分页签
			var page = $("#pageChat").val();
			page = $(".main_nav_tell > div").size();
			page = page <0 ? 0 : page;
			setTimeout(function() {
				var data = {from : ct.usercount,to : to,page : page};
				$("#pageChat").val(page);
				$.post(ct.chat_contextPath+"chatCacheController/loadChatLogPage.html",data,function(object){
					if(object.length!=0){
						$.each(object,function(i,u){
							//u = chatMsgObject
							var str =  ct.prototy.lmORrm(u);
							$(".main_nav_tell").prepend(str);
						});
						$('.fancybox').fancybox();
					}else{
						alert('已是最后一页了!!!');
					}
				},"json");
			 },1000);//延时一秒
			 return;
		},
		 
		/**
		 * 上传文件控件
		 */
		 uploadFile:function(){
			 var $ = jQuery,
		        $list = $('#chat-uploader-list'),
		        btn = '#chat-file-upload-btn',
		        state = 'pending',
		        uploader;

		    uploader = WebUploader.create({
		        resize: true,
		        // swf文件路径
		        swf:  chat_contextPath+'uploadify/Uploader.swf',

		        // 文件接收服务端。
		        server: chat_contextPath+'fileChatController/douploadfile.do?randtime='+Date.parse(new Date()),
		        auto: true,
		        multiple: false,
		        fileNumLimit:1,
		        //   fileSingleSizeLimit: 1 * 1024 * 1024 ,   // 50 M
		        // 选择文件的按钮。可选。
		        // 内部根据当前运行是创建，可能是input元素，也可能是flash.
		        pick: btn

		    });
		    resizeUpload($('.file-upload-btn'), '21px', '17px');
		    // 当有文件添加进来的时候
		    uploader.on( 'fileQueued', function( file ) {
		        $list.append( '<div id="' + file.id + '" class="item">' +
		        '<div class="uploadfile-header"><div class="info left">' + file.name + '</div><a href=""  class="right uploadify-cancel" ><img src="'+chat_contextPath+'images/uploadify-cancel.png"></a></div>' +
		        '<p class="state">等待上传...</p>' +
		        '</div>' );
		        $('.uploadify-cancel').on('click', 'img', function() {
		            uploader.cancelFile( file );
		        });
		    });

		    // 文件上传过程中创建进度条实时显示。
		    uploader.on( 'uploadProgress', function( file, percentage ) {
		        var $li = $( '#'+file.id ),
		            $percent = $li.find('.progress .progress-bar');

		        // 避免重复创建
		        if ( !$percent.length ) {
		            $percent = $('<div class="progress progress-striped active">' +
		            '<div class="progress-bar" role="progressbar" style="width: 0%">' +
		            '</div>' +
		            '</div>').appendTo( $li ).find('.progress-bar');
		        }

		        $li.find('p.state').text('上传中');

		        $percent.css( 'width', percentage * 100 + '%' );
		    });


		    uploader.on( 'uploadSuccess', function( file,response) {
		        $( '#'+file.id ).find('p.state').text('已上传');
//		        var obj = eval("("+data+")");
		        if(response._raw == undefined){
        			response = response;
    			}else{
    				response = eval("("+response._raw+")");
    			}
            	if(response.result=="000000"){
            		//文件上传成功
            	    ct.prototy.messageStr(response.ext,response.object.id,response.object.aftername,response.object.beforename,response.object.size);
            		//alert(connection);
            	}
		    });

		    uploader.on( 'uploadError', function( file ) {
		        $( '#'+file.id ).find('p.state').text('上传出错');
		    });

		    uploader.on( 'uploadComplete', function( file ) {
		        init();
		        resizeUpload($('.file-upload-btn'), '21px', '17px');
		        $( '#'+file.id ).fadeOut();
		        uploader.reset();
		    });

		    uploader.on( 'all', function( type ) {
		        if ( type === 'startUpload' ) {
		            state = 'uploading';
		        } else if ( type === 'stopUpload' ) {
		            state = 'paused';
		        } else if ( type === 'uploadFinished' ) {
		            state = 'done';
		        }
		    });
		},
		/**
		 * 组装消息
		 * @param ext 文件类型
		 * @param fileid 文件id
		 * @param fileName 文件名
		 * @param orgName 原始文件名
		 * @param size 文件大小
		 * doc;*.docx;*.ppt;*.pptx;*.xls;*.xlsx;*.zip;*.rar;*.txt
		 * @return
		 */
		messageStr:function (ext,fileid,fileName,orgName,size){
			//bmp,gif,jpeg,jpg,png图下
			var str = "";
			var msgType = ct.msgType.pic;
			var account = $(".content_nav").attr("account");
			var sessionType = $(".content_nav").attr("sessionType");
			
			
			str = "{\"fileid\":\""+fileid+"\",\"ext\":\""+ext+"\",\"fileName\":\""+fileName+"\",\"orgName\":\""+orgName+"\",\"size\":\""+size+"\"}";
			if(ext=='bmp' || ext=='gif' || ext=='jpeg' || ext=='jpg' || ext=='png'){
				msgType = ct.msgType.pic;
			}else if(ext=='doc' || ext=='docx' || ext=='ppt' || ext=='pptx' || ext=='xls' || ext=='xlsx' || ext=='zip' || ext=='rar' || ext=='txt' ){
				//sendMsg(str , "1");  cht("<![CDATA[{\"msgType\":\""+type+"\",\"content\":"+msg+",\"sendtime\":\""+sendtime+"\"}]]>")
				msgType = ct.msgType.file;
			}else{
				msgType = ct.msgType.file;
			}
			
			if(sessionType == ct.sessionType.groupE){
				ct.prototy.sendGroupMsg(msgType,str ,account);
			}else{ 
				ct.prototy.sendMsg(msgType,str ,account);
			}
		}
		//end
	  };//属性结束符
}
